import javax.swing.*;
import java.awt.*;
import java.util.HashMap;
import java.util.Stack;

public class CalculatorDemo extends JFrame {

    private Stack<Double> expressionValue = new Stack<>(); // 值
    private Stack<String> expressionOperator = new Stack<>(); // 运算符

    private CalculatorDemo() {

        setTitle("基于 Java 的计算器");
        setSize(345, 500);
        setLocation(700, 300);
        Container c = getContentPane();
        c.setLayout(null);

        // 输入面板
        JTextArea jt = new JTextArea(100, 100);
        jt.setFont(new Font("Aria", Font.BOLD, 30));
        jt.setLineWrap(true);
        JScrollPane sp = new JScrollPane(jt);
        jt.setCaretPosition(jt.getDocument().getLength());
        sp.setBounds(0, 0, 330, 163);
        c.add(sp);

        JPanel p = new JPanel();
        p.setLayout(new GridLayout(5, 4, 0, 0));
        p.setBounds(0, 162, 340, 300);

        // 放置按钮
        int n = 20;
        String[] num = {
                "C", "(", ")", "/",
                "7", "8", "9", "*",
                "4", "5", "6", "-",
                "1", "2", "3", "+",
                "0", ".", "DEL", "="
        };
        JButton[] jb = new JButton[n];
        for (int i = 0; i < n; i++) {
            jb[i] = new JButton(num[i]);
            p.add(jb[i]);
        }
        c.add(p);

        for (int i = 1; i < 18; i++) {
            final int j = i;
            jb[i].addActionListener(e -> jt.append(num[j]));
        }


        // 监听 C 按键
        jb[0].addActionListener(e->{
            jt.setText("");
            expressionValue.clear();
            expressionOperator.clear();
        });

        // 监听 DEL 按键
        jb[18].addActionListener(e->{
            try {
                jt.setText(jt.getText().substring(0,jt.getText().length()-1));
            } catch (Exception ignored) {

            }
        });

        // 监听 = 按键
        jb[19].addActionListener(e->{
            try {
                System.out.println(jt.getText());
                double x = calculate(jt.getText() + "#");
                jt.setText("");  				// 清空输入框
                jt.append(String.valueOf(x)); 	// 显示计算结果
            } catch(Exception ex) { 			// 异常情况
                if(ex.getMessage() == null) {
                    jt.setText("计算错误!");
                } else {
                    jt.setText(ex.getMessage());
                }
            }
        });

        KeyStroke enter = KeyStroke.getKeyStroke("ENTER");
        jt.getInputMap().put(enter, "none");

        this.getRootPane().setDefaultButton(jb[19]);

        setVisible(true);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }

    // 执行 + - * / 计算
    private void calculate(){
        String b = expressionOperator.pop();
        double c = expressionValue.pop();
        double d = expressionValue.pop();
        double e;

        if (b.equals("+")) {
            e = d + c;
            expressionValue.push(e);
        } else if (b.equals("-")) {
            e = d - c;
            expressionValue.push(e);
        } else if (b.equals("*")) {
            e = d * c;
            expressionValue.push(e);
        } else if (b.equals("/")) {
            if(c == 0)
                throw new ArithmeticException("除 0 错误!");
            e = d / c;
            expressionValue.push(e);
        }
    }

     //计算字符串的值
    private Double calculate(String text){
        HashMap<String, Integer> operator = new HashMap<>();
        operator.put("(",0);
        operator.put(")",0);
        operator.put("/",2);
        operator.put("*",2);
        operator.put("-",1);
        operator.put("+",1);
        operator.put("#",0);

        expressionOperator.push("#");

        int flag = 0;
        int n = text.length();
        for(int i = 0; i < n; i++) {
            String a = String.valueOf(text.charAt(i));
            if (!a.matches("[0-9.]")) {
                if(flag != i) {
                    expressionValue.push(Double.parseDouble(text.substring(flag, i)));
                }
                flag = i + 1;
                while(!(a.equals("#") && expressionOperator.peek().equals("#"))) { // peek 返回栈顶元素，不删除
                    if(operator.get(a) > operator.get(expressionOperator.peek()) || a.equals("(")) {
                        expressionOperator.push(a); // 加入操作符
                        break;
                    } else {
                        if(a.equals(")")) {
                            while(!expressionOperator.peek().equals("("))
                                calculate();
                            expressionOperator.pop();
                            break;
                        }
                        calculate();
                    }
                }

            }
        }

        return expressionValue.pop();
    }

    public static void main(String[] args) {
        new CalculatorDemo();
    }
}